<template>
  <div class="html2canvas clearfix">
    <el-scrollbar style="height: 100%">
    <div class="main">
      <el-card class="box-card mb15" shadow="hover">
        <div slot="header" class="clearfix">
          <span class="fs16"><a class="ml5" target="_blank" href="http://html2canvas.hertzen.com">http://html2canvas.hertzen.com</a></span>
        </div>
        <div class="fs14 p10 lh20 text-left">
          <code>
            npm install html2canvas<br>
            <br>
            import html2canvas from 'html2canvas';<br>
            html2canvas(document.body).then(function(canvas) {<br>
                &nbsp;&nbsp;document.body.appendChild(canvas);<br>
            });
          </code>
        </div>
      </el-card>
      <div>
        <!-- SOURCE -->
        <div id="text-canvas" ref="printMe">
          <img src="../assets/logo.png">
          <el-badge :value="12" class="item">
            <el-button size="small">评论</el-button>
          </el-badge>
        </div>
        <button class="m20" @click="print">Print me!</button>
        <!-- OUTPUT -->
        <img class="text-img block mt20" :src="output">
      </div>
    </div>
    </el-scrollbar>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'

export default {
  name: 'Html2Canvas',
  data () {
    return {
      output: null
    }
  },
  methods: {
    print () {
      let that = this
      html2canvas(document.getElementById('text-canvas')).then(function (canvas) {
        that.output = that.convertCanvasToImage(canvas)
        // document.body.appendChild(canvas)
      })
    },
    // 将canvas转为image
    convertCanvasToImage (canvas) {
      // 新Image对象，可以理解为DOM
      var image = new Image()
      // canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持
      // 指定格式 PNG
      image.src = canvas.toDataURL('image/png')
      return image.src
    },
    // 将image转为canvas
    convertImageToCanvas (image) {
      // 创建canvas DOM元素，并设置其宽高和图片一样
      var canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      // 坐标(0,0) 表示从此处开始绘制，相当于偏移。
      canvas.getContext('2d').drawImage(image, 0, 0)
      return canvas
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
.html2canvas{
  margin: 0 auto;
  overflow: hidden;
  .main{
    padding: 10px;
    .text-img{
      width: 80%;
      margin: 0 auto;
      height: auto;
    }
  }
}
</style>
